#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.

""" 
Created on 2010-12-23 
@author: DOC 
"""
import pymongo
#from pymongo.objectid import ObjectId
from config import conf

class mongo_class():
    conn=False
    db=False
    tab=False
    auth=False
    
    def __init__(self):
        self.conn = False
        self.db = False
        self.tab = False
        self.auth = True
#        self.mongoconn("127.0.0.1",27017,"qq","qqgame","pH65EYLJhb2vdnKL")
        self.mongoconn(conf.get("MONGO_IP"),int(conf.get("MONGO_POST")),conf.get("MONGO_DB"),conf.get("MONGO_USER"),conf.get("MONGO_PWD"))
        
    def mongoconn(self,local,post,mongodb,username="",pwd=""):
        conn = pymongo.Connection(local,post)  # 创建数据库连接
        if(conn==False):
            print("链接mongo失败")
            exit()
            return False

        self.db = conn[mongodb]   # 得到数据库
        if(self.db==False):
            print("链接mongo数据库失败")
            exit()
            return False
            
        if(username and pwd):
            self.auth = self.db.authenticate(username,pwd)   #验证用户密码
            if(self.auth==False):
                print("链接mongo密码验证失败")
                exit()
                return False
        print("mongo准备就绪")
        return True
    
    def mongotab(self,tab):
        if(self.auth):
            self.tab = self.db[tab]           # 获得表
            return True
        return False
            
#    def objectid(self,listid):
#        return ObjectId(listid)
            
    def find(self,tab,query=None,show=None):
        if(self.mongotab(tab)):
            return self.tab.find(query,show)
        else:
            print("打开数据表失败")
            return None
        
    def findone(self,tab,query=None,show=None):
        if(self.mongotab(tab)):
            return self.tab.find_one(query,show)
        else:
            print("打开数据表失败")
            return None
    
    def findsort(self,tab,query=None,show=None,sorts=None):
        if(self.mongotab(tab)):
            if(sorts[1]>=0):
                return self.tab.find(query,show).sort(sorts[0],pymongo.ASCENDING)
            else:
                return self.tab.find(query,show).sort(sorts[0],pymongo.DESCENDING)
        else:
            print("打开数据表失败")
            return None
    
    def add(self,tab,datas=None):
        if(self.mongotab(tab)):
            return self.tab.save(datas)
        else:
            print("打开数据表失败")
            return None
      
    def delete(self,tab,query=None):
        #collor.remove() # 删除所有
        if(self.mongotab(tab)):
            return self.tab.remove(query)
        else:
            print("打开数据表失败")
            return None
          
    def update(self,tab,datas=None,query=None):
        if(self.mongotab(tab)):
            return self.tab.update(query,{'$set':datas},upsert=True,multi=True)
        else:
            print("打开数据表失败")
            return None
            
      
    def find_limit(self,tab,query=None,show=None,skip=0,limit=1):     # 检索第 2、3条记录：skip(>=), limit(<=)  
        if(self.mongotab(tab)):
            return self.tab.find(query,show).skip(int(skip)).limit(int(limit))
        else:
            print("打开数据表失败")
            return None
           
    #插入数据 
    def insert(self,tab,data):
        if(self.mongotab(tab)):
            return self.tab.insert(data)
        else:
            print("打开数据表失败")
            return None
        
    #找出对应最大值
    def max_id(self,tab,filed="id"):
        if(self.mongotab(tab)):
            query=None
            show={filed:True}
            #ASCENDING升序
            aat=self.tab.find(query,show).sort(filed,pymongo.DESCENDING).limit(1)
            for m in aat:
                if (m.has_key(filed)):
                    return m[filed]+1
            return 1
        else:
            print("打开数据表失败")
            return 1

    def group(self,table,keys,conds={},sort_key=False,sort_type=True):
        """
        * 数据分组
        * @access    Public
        * @param    string    table      表名
        * @param    string    keys        要分组的字段
        * @param    string    conds        查询条件
        * @param    string    sort_key    排序字段
        * @param    string    sort_type    排序类型 True逆序 False顺序
        """
        if(sort_key==False):
            sort_key=keys
        self.mongotab(table)
        gkeys ={keys:1}
        
        if(keys==sort_key):
            initials = {"items" :{keys:1},"index":-1,"total":0}
        else:
            initials = {"items" : {keys:1,sort_key:1},"index":-1,"total":0}
        
        
        reduces = "function (obj, prev){prev.total+=1}"
        
        g = self.tab.group(key=gkeys, initial=initials, reduce=reduces,condition=conds)

        sorted(g, key=lambda x:x[sort_key],reverse=sort_type)
        
        return g
    
    def sums(self,table,groups,keys,conds={},sort_key=False,sort_type=True):
        """
        * 数据统计
        * @access    Public
        * @param    string    table      表名
        * @param    string    groups      要分组的字段
        * @param    string    keys        要统计的字段
        * @param    string    conds        查询条件
        * @param    string    sort_key    排序字段
        * @param    string    sort_type    排序类型 True逆序 False顺序
        """
        if(sort_key==False):
            sort_key=groups
        self.mongotab(table)
        gkeys ={groups:1}
        
        if(groups==sort_key):
            initials = {"items" :{groups:1},"index":-1}
        else:
            initials = {"items" : {groups:1,sort_key:1},"index":-1}

        if(type(keys)==list):
            qe=""
            for k in keys:
                initials["items"][k]=1
                initials[k]=0
                qe+="prev."+k+"+=obj."+k+";"
            reduces = "function (obj, prev){"+qe+"}"
        else:
            initials["items"][keys]=1
            initials[keys]=0
            reduces = "function (obj, prev){prev."+keys+"+=obj."+keys+"}"
        
        g = self.tab.group(key=gkeys, initial=initials, reduce=reduces,condition=conds)
        
        sorted(g, key=lambda x:x[sort_key],reverse=sort_type)
        return g
    